package com.my.blog.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.blog.myblog.entity.Visit;
import com.my.blog.myblog.mapper.VisitMapper;
import com.my.blog.myblog.service.VisitService;
import com.my.blog.utils.AddressUtil;
import com.my.blog.utils.UserIpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

/***
 *
 * @Auther: MuYun
 * @Date: 2021/10/12 13:57
 * @Description： 访客的监听器
 * 此注解声明此类为listener，无需再进行配置，唯一注意的是，
 * 使用注解的方式声明Listener时，需要在main函数类上添加@ServletComponentScan(basePackages='此处写明类地址，格式为包名+类名')
 */
@WebListener
public class VisitListener implements ServletRequestListener {

    @Autowired
    private VisitMapper visitMapper;

    @Override
    public void requestInitialized(ServletRequestEvent event){
        //System.out.println("访客监听启动..");
        WebApplicationContextUtils.getRequiredWebApplicationContext(event.getServletContext())
                .getAutowireCapableBeanFactory().autowireBean(this);
        //获取当前进来的request请求
        HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
        //获取session
        HttpSession session = request.getSession();
        //初始化访客
        Visit visit=null;
        try {
            if(session.isNew()){
                //获取请求的ip地址
                String ip = UserIpUtil.getIp(request);
                //获取请求的用户和浏览器信息
                String useragent = request.getHeader("user-agent");
                visit=new Visit();
                visit.setIp(ip);
                visit.setUserAgent(useragent);
                visit.setTime(LocalDateTime.now());
                //获取当前时间前推24小时的的具体时间
                LocalDateTime dateTime=LocalDateTime.now().minusHours(12);
                //检索该ip在24小时内有没有访客记录
                QueryWrapper<Visit> queryWrapper=new QueryWrapper<>();
                queryWrapper.lambda().eq(Visit::getIp,ip);
                queryWrapper.lambda().eq(Visit::getUserAgent,useragent);
                queryWrapper.lambda().ge(Visit::getTime,dateTime);
                UserAgent userAgent = UserAgentUtil.parse(useragent);
                //针对可能请求过多引起插入错乱，采用同步锁
                synchronized (this){
                    //如果该ip在24小时内没有访客记录，则记录该ip
                    if(visitMapper.selectList(queryWrapper).size()==0){
                        visit.setBrowserType(userAgent.getBrowser().toString()+"  "+userAgent.getVersion());
                        visit.setPlatformType(userAgent.getPlatform().toString());
                        visit.setUrl(request.getRequestURL().toString());
                        //通过ip和编码获取ip对应地址
                        visit.setCity(new AddressUtil().getAddresses("ip="+ip,"GBK"));
                        System.out.println(visit);
                        visitMapper.insert(visit);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
